/*
 * @Description: 打印弹窗
 * @Author: Rfan
 * @Date: 2022-09-30 18:15:08
 * @LastEditTime: 2023-01-06 14:08:37
 */

import { useEffect, useState } from 'react';
import { Button, Checkbox, List, Modal, Space, Tabs } from 'antd';
import type { ICommonDialog, ICoordinate } from '@/interfaces/global';
import { downloadBaseurl, fetchReportList, reportMutiPreviewUrl } from '@/api/report';
import { selectItemByKey } from '@/utils/list';

const { TabPane } = Tabs;

/**
 * @description: 打开新页面
 * @param {string} url 页面url
 */
const openReportTemp = (url: string) => {
  window.open(url);
};

interface IPrintProps extends ICommonDialog {
  selectItems: number[];
  baseInfo: any;
}

const PrintDialog = (props: IPrintProps) => {
  const { visible, selectItems, onClose, baseInfo } = props;

  // 展示的模板列表
  const [tempList, setTempList] = useState<any>([]);
  // 选中的模板
  const [tempObjs, setTempObjs] = useState([]);
  // 打印弹窗展示状态
  const [selectTab, setSelectTab] = useState('');
  // 打印弹窗展示状态
  const [printVisible, setPrintVisible] = useState(false);

  useEffect(() => {
    if (visible) {
      // 请求打印模板类型
      const params: ICoordinate = {
        atCode: baseInfo.atCode,
        atType: baseInfo.atType,
        level: baseInfo.atlevel
      };
      fetchReportList(params).then((res) => {
        setSelectTab(res.data[0].id);
        setTempList(res.data);
      });
    } else {
      setTempObjs([]);
      setSelectTab('');
    }
  }, [visible]);

  const onCancel = (data: any) => {
    onClose(data);
  };

  const setSelectTemp = (ids: number[]) => {
    setTempObjs(ids.map((id) => selectItemByKey(id, tempList)));
  };

  /**
   * @description:  显示模板预览列表
   */
  const showPrintItemList = () => {
    if (selectItems.length === 1 && tempObjs.length === 1) {
      // 只选一个条目一种类型时直接预览
      openPreview(selectItems);
    } else {
      setSelectTab(tempList[0].id);
      setPrintVisible(true);
    }
  };

  /**
   * @description: 打开预览模板页面
   * @param {number | number[]} ids 链接参数
   */
  const openPreview = (ids: number | number[]) => {
    const idsStr = ids instanceof Array ? ids.join(',') : ids;
    const currentTemp = selectItemByKey(selectTab, tempList);
    const urlProps = {
      templateId: currentTemp.id,
      ids: idsStr
    };
    const propsArr = Object.entries(urlProps)
      .map(([key, val]) => `${key}=${val}`)
      .join('&');

    const previewUrl = reportMutiPreviewUrl(urlProps);
    console.log('previewFetch', previewUrl);
    openReportTemp(`${previewUrl}`);
  };

  /**
   * @description: 打开下载页面
   * @param {number | number[]} ids 链接参数
   */
  const openDownload = (ids: number | number[]) => {
    const idsStr = ids instanceof Array ? ids.join(',') : ids;
    const currentTemp = selectItemByKey(selectTab, tempList);
    const urlProps = {
      fileName: currentTemp.name,
      templateId: currentTemp.id,
      ids: idsStr
    };
    const propsArr = Object.entries(urlProps)
      .map(([key, val]) => `${key}=${val}`)
      .join('&');

    openReportTemp(`${downloadBaseurl}?${propsArr}`);
  };

  /**
   * @description:  打印选中模板方法
   */
  const printCurrentTemp = () => {
    openPreview(selectItems);
  };

  /**
   * @description:  一键下载
   */
  const downloadCurrentTemp = () => {
    openDownload(selectItems);
  };

  // const closePrintListDialog = () => {
  //   setPrintVisible(false);
  //   onClose();
  // };

  return (
    <Modal
      destroyOnClose
      title="打印"
      visible={visible}
      width={400}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button
          key="print"
          onClick={() => {
            showPrintItemList();
          }}
        >
          打印
        </Button>
      ]}
    >
      <div>
        <p>请选择以下模板</p>
        <Checkbox.Group value={tempObjs.map((item) => item.id)} onChange={setSelectTemp}>
          <Space direction="vertical">
            {tempList.map((item: any) => (
              <Checkbox value={item.id}>{item.name}</Checkbox>
            ))}
          </Space>
        </Checkbox.Group>
      </div>
      <Modal
        destroyOnClose
        title="打印"
        visible={printVisible}
        width={600}
        onCancel={() => {
          setPrintVisible(false);
        }}
        footer={[
          <Button
            key="download"
            onClick={() => {
              downloadCurrentTemp();
            }}
          >
            一键下载
          </Button>,
          <Button
            key="print"
            onClick={() => {
              printCurrentTemp();
            }}
          >
            一键打印
          </Button>
        ]}
      >
        <Tabs
          onChange={(value: string) => {
            setSelectTab(value);
          }}
        >
          {tempObjs.map((item) => (
            <TabPane tab={item.name} key={item.id}>
              <List
                itemLayout="horizontal"
                dataSource={selectItems}
                renderItem={(id) => (
                  <List.Item
                    actions={[
                      <Button
                        type="link"
                        onClick={() => {
                          openPreview(id);
                        }}
                      >
                        预览
                      </Button>
                    ]}
                  >
                    <List.Item.Meta title={`${id} - ${item.name}`} />
                  </List.Item>
                )}
              />
            </TabPane>
          ))}
        </Tabs>
      </Modal>
    </Modal>
  );
};

export default PrintDialog;
